package org.lql.chaos.mq.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.lql.chaos.mq.rabbitmq.constant.RabbitMQConstant;
import org.lql.chaos.mq.rabbitmq.pojo.OrderInfo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author: liangqinglong
 * @date: 2025-08-09 00:16
 * @description:
 **/
@Slf4j
@Component
public class OrderMessageConsumer {

	@RabbitListener(queues = RabbitMQConstant.ORDER_DEAD_QUEUE)
	public void handleDeadMessage(OrderInfo orderInfo, Message message, Channel channel) {
		try {
			log.info("订单超时未支付，自动取消订单：{}", JSONObject.toJSONString(orderInfo));


			// TODO: 实际的订单取消业务逻辑

			// 确认消息
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (Exception e) {
			log.error("订单超时未支付，自动取消订单失败：{}", e.getMessage());
			try {
				// 拒绝消息并不再次入队
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
			} catch (Exception ex) {
				log.error("确认消息失败：{}", ex.getMessage(), ex);
			}
		}
	}
}
